package org.springframe.postProcessor;

import org.springframe.annotation.Aspect;
import org.springframe.aop.AopProxy;
import org.springframe.aop.SpringAopAutoProxyFactory;

import java.util.HashSet;
import java.util.Set;

/**
* @package  org.springframe.postProcessor
* @classname AopProxyCreatorBeanPostProcessor
* @description AOP实现类
* @version 1.0
* @author luoweiwei
* @date  2021-04-25 09:55:09
*/
public class AopProxyCreatorBeanPostProcessor implements BeanPostProcessor {

    private Set<Class> classSet;

    private Set<Class> aspectClassSet;

    public AopProxyCreatorBeanPostProcessor(Set<Class> classSet,Set<Class> aspectClassSet) {
        this.classSet = classSet;
        this.aspectClassSet = aspectClassSet;
    }

    private Set<String> proxyClassSet = new HashSet<>();

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
        Class<?> clazz;
        try {
            if(!proxyClassSet.contains(beanName)&&(clazz = isNeedProxy(bean))!=null){
                //生成代理类 替换bean
                SpringAopAutoProxyFactory proxyFactory = new SpringAopAutoProxyFactory();
                AopProxy proxy =  proxyFactory.createProxy(bean,clazz,aspectClassSet);
                bean = proxy.getProxy();
                proxyClassSet.add(beanName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    private Class<?> isNeedProxy(Object bean){
        for (Class aClass : classSet) {
            if(aClass.isAssignableFrom(bean.getClass())){
                return aClass;
            }
        }
        return null;
    }
}
